package com.kingsoft.dc.khaos.module.mpp.sql;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingsoft.dc.khaos.module.mpp.auth.MppSqlAuthentication;
import com.kingsoft.dc.khaos.module.mpp.utils.FileUtils;
import com.kingsoft.dc.khaos.plugin.core.constants.ScheduleConstants;
import com.kingsoft.dc.khaos.plugin.core.exception.PermissionException;
import com.kingsoft.dc.khaos.plugin.core.metadata.PluginModule;
import com.kingsoft.dc.khaos.plugin.core.metadata.StrategyInfo;
import com.kingsoft.dc.khaos.plugin.core.utils.ConfigUtils;
import org.apache.commons.lang.StringUtils;

import java.util.Properties;

/**
 * Created by jing on 19/8/2.
 */
public class MppSql extends PluginModule {
    private StrategyInfo strategyInfo;

    private SqlStrategy strategy;

    @Override
    public Object prepare() {
        log().info("MppSql prepare start...");
        String conf = getModuleConfiguration();
        if (conf == null) {
//            throw new IllegalAccessException("conf is null");
        }
        Properties config = ConfigUtils.init();
        for (Object key :  config.keySet()) {
            getKhaosContext().getConf().set((String) key, config.get(key));
        }
//        log().info("getKhaosContext:{}", JSONObject.toJSON(getKhaosContext().getConf()));
//        log().info("getKhaosContext_db_name:{}", (getKhaosContext().getConf().getSetting()));

        strategyInfo = JSON.parseObject(conf, StrategyInfo.class);
        try {
            strategy = (SqlStrategy) Class.forName(strategyInfo.getClazz(), true, Thread.currentThread().getContextClassLoader())
                    .newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        log().info("MppSql prepare end...");
        return null;
    }

    @Override
    public Object execute() throws Exception {
        MppSqlConfig config = JSON.parseObject(strategyInfo.getConfig(), MppSqlConfig.class);
        log().info("read sqlFile start...");
        String sql = FileUtils.readFileToString(khaosContext.getConf().getString(ScheduleConstants.COMMAND_FILE));
        log().info("read sqlFile end...");
        String  dbName =config.getExtender().getAuth().getParams().getDbName();
        log().info("schema_dbname:" + dbName);
        if (isBlank(sql)) {
            log().info("sql为空");
            return null;
        }
        config.setSql(sql);
        MppSqlAuthentication mppSqlAuth = new MppSqlAuthentication();
        log().info("开始校验权限...");
        if (!mppSqlAuth.authenticate(khaosContext, config)) {
            throw new PermissionException("has no permission to access table.");
        }
        if (StringUtils.isNotBlank(dbName)){
            sql = "set search_path to" +" "+"\""+ dbName +"\""+ ";\n" + sql;
            config.setSql(sql);
        }
        strategy.execute(khaosContext, moduleId, config);
        return null;
    }

    @Override
    public String getModuleConfiguration() {
        return khaosContext.getConf().getString(moduleId);
    }


    public static boolean isBlank(String input) {
        if (input == null || "".equals(input))
            return true;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }
}
